package com.eastseeway.radioproject.unlock;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.util.Log;

import androidx.lifecycle.LiveData;

import com.amap.api.location.AMapLocation;
import com.eastseeway.radioproject.R;
import com.eastseeway.radioproject.RadioApplication;
import com.eastseeway.radioproject.RxLocation.LocationRequester;
import com.eastseeway.radioproject.base.BaseRepository;
import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.database.RadioProjectDatabase;
import com.eastseeway.radioproject.database.UserInfoDao;
import com.eastseeway.radioproject.database.VersionInfoDao;
import com.eastseeway.radioproject.entities.BaseResponse;
import com.eastseeway.radioproject.entities.OperationParams;
import com.eastseeway.radioproject.entities.UserInfo;
import com.eastseeway.radioproject.entities.VersionBean;
import com.eastseeway.radioproject.retrofit.RetrofitClient;
import com.eastseeway.radioproject.utils.CommandGenerator;
import com.eastseeway.radioproject.utils.SPHelper;
import com.eastseeway.radioproject.utils.SaveHelper;
import com.eastseeway.radioproject.utils.TimeUtils;
import com.eastseeway.radioproject.utils.XLogUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Callback;

public class UnlockRepository extends BaseRepository {

    private final UserInfoDao mUserInfoDao;
    private final VersionInfoDao mVersionInfoDao;


    public UnlockRepository() {
        super();
        mUserInfoDao = RadioProjectDatabase.getInstance(RadioApplication.getInstance()).getUserInfoDao();
        mVersionInfoDao = RadioProjectDatabase.getInstance(RadioApplication.getInstance()).getVersionInfoDao();
    }

    public LiveData<UserInfo> queryUserByUsername(String username){
        return mUserInfoDao.queryUser(username);
    }

    public LiveData<UserInfo> queryAdmin(){
        return mUserInfoDao.queryAdmin();
    }



    public String queryVersionCodeByAddress(String softStyle){
        try {
            Future<String> future = executorService.submit(()-> mVersionInfoDao.queryVersionCodeInfo(softStyle));
            return future.get();
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    public void insertVersionInfo(VersionBean versionBean){
        executorService.submit(()->{
            mVersionInfoDao.addVersionInfo(versionBean);
        });

    }
    public LiveData<List<UserInfo>> queryAllUsers(){
        return mUserInfoDao.queryAll();
    }

    public LiveData<List<VersionBean>> queryAllVersion() {
        return mVersionInfoDao.queryAllVersion();
    }

    /**
     * 初始化管理员和预置参数 0-4是每个手柄的预置参数，5是最后一次使用的参数
     */
    public void insertAdmin(){
        executorService.submit(()->{
            UserInfo userInfo = new UserInfo();
            userInfo.setId(1);
            userInfo.setIs_admin(true);
            userInfo.setName("admin");
            userInfo.setPassword("000000");
            mUserInfoDao.addUser(userInfo);
//            HashMap<String,List<OperationParams>> map = new HashMap<>();
//            List<OperationParams> pressureOperationParamsList = new ArrayList<>();
//            List<OperationParams> nPressureOperationParamsList = new ArrayList<>();
            for (int i = 0; i < Const.POSITION_PREVIOUS_PARAMS; i++) {
                OperationParams operationParams = new OperationParams();
                operationParams.setId(CommandGenerator.generateId(userInfo.getId(),true,(i+1)));
                operationParams.setHasPressure(true);
                operationParams.setPosition(i+1);
                operationParams.setUsername("admin");
                operationParams.setEmpty(true);
//                pressureOperationParamsList.add(operationParams);
                mUserInfoDao.insertOrUpdateOperationParams(operationParams);
            }
            for (int i = 0; i < Const.POSITION_PREVIOUS_PARAMS; i++){
                OperationParams operationParams = new OperationParams();
                operationParams.setId(CommandGenerator.generateId(userInfo.getId(),false,(i+1)));
                operationParams.setHasPressure(false);
                operationParams.setPosition(i+1);
                operationParams.setUsername("admin");
                operationParams.setEmpty(true);
//                nPressureOperationParamsList.add(operationParams);
                mUserInfoDao.insertOrUpdateOperationParams(operationParams);
            }
            try {
                Runtime.getRuntime().exec("sync");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
//            map.put("pressure",pressureOperationParamsList);
//            map.put("nPressure",nPressureOperationParamsList);
//            SaveHelper.write2File(SaveHelper.getOperationParamsFilePath(userInfo.getName()),new Gson().toJson(map));
        });
    }

    @SuppressLint("CheckResult")
    protected void getLocationAddress(Application application) {
        new LocationRequester<AMapLocation>().requestLocation()
                .take(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aMapLocation -> {
                    Log.e("12121","获得位置信息： "+aMapLocation.getLocationType());
                    String currentTime = TimeUtils.getCurrentTime(TimeUtils.FORMAT_DATE_TIME_FULL1);
//                    SPHelper.saveAddress(RadioApplication.getAppContext(),aMapLocation.getAddress());
//                    将位置信息写入文件中
//                    SaveHelper.write2File(currentTime + "  " +aMapLocation.getAddress());
                    XLogUtils.logUserAction(currentTime + "  " +aMapLocation.getAddress());
//                    将位置信息上报服务器
                    Map map = new HashMap<String, Object>();
                    map.put("DeviceCode", SPHelper.getDeviceId(application)); //设备编号
                    map.put("MessageStyle", "Real"); //消息类型   Real(心跳包)  Data（查询的数据）  Param （参数信息）
                    map.put("MessageTime", currentTime); //消息时间
                    map.put("Latitude", aMapLocation.getLatitude()); //经度
                    map.put("Longitude", aMapLocation.getLongitude()); //纬度
                    map.put("Location", "222"+aMapLocation.getAddress());//详细位置信息
                    map.put("Data", "");
                    String jsonStr = new Gson().toJson(map);
                    testRabbitMq(jsonStr);
//                    RabbitMQUtil.getInstance().sendPropertyMessage(jsonStr, isSuccess -> Log.e("12121","sendMessage: "+isSuccess));
                });
    }


    protected void checkAppUpdate(String deviceId, Callback<BaseResponse<List<VersionBean>>> callback){
        RetrofitClient.getInstance().getServiceApi().checkAppUpdate(deviceId).enqueue(callback);
    }

    void uploadVersionInfos(String deviceId,String versionInfo,Callback<BaseResponse<String>> callback){
        RetrofitClient.getInstance().getServiceApi().uploadVersionInfos(deviceId,versionInfo).enqueue(callback);
    }

    public void createFile() {
        SaveHelper.createLogDirectory();
        SaveHelper.createOperationParamsDirectory();
    }

    public void testRabbitMq(String jsonStr) {
        executorService.submit(()->{
            ConnectionFactory factory = new ConnectionFactory();
            // 连接配置
            factory.setHost(RadioApplication.getInstance().getString(R.string.mq_address)); // 服务器ip
            factory.setPort((Const.MQ_PORT)); // 端口
            factory.setUsername(Const.MQ_USERNAME); // 用户名
            factory.setPassword(Const.MQ_PASSWORD); // 密码
            factory.setVirtualHost(Const.MQ_VIRTUAL_HOST);
            // 创建消息的properties
            AMQP.BasicProperties.Builder propertiesBuilder = new AMQP.BasicProperties.Builder();
            propertiesBuilder.deliveryMode(2); // 设置消息持久化
            propertiesBuilder.contentType("application/json");
            propertiesBuilder.priority(0); // 设置消息优先级
            propertiesBuilder.contentEncoding("UTF-8");
            Map propertiesMap=new HashMap<String,Object>();
            propertiesMap.put("__ContentTypeId__","java.lang.Object");
            propertiesMap.put("__KeyTypeId__","java.lang.String");
            propertiesMap.put("__TypeId__","org.jeecg.common.base.BaseMap");
            propertiesBuilder.headers(propertiesMap);

            AMQP.BasicProperties properties = propertiesBuilder.build();
            Connection connection = null;
            Channel channel = null;

            try {
                connection = factory.newConnection();
                channel = connection.createChannel();
                try {
                    // 发布消息到队列
                    channel.basicPublish(Const.MQ_EXCHANGE_NAME, Const.MQ_ROUTING_KEY, properties,jsonStr.getBytes());

                } finally {
                    if (channel != null) {
                        channel.close();
                    }
                    if (connection != null) {
                        connection.close();
                    }
                }

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        });
    }

    public LiveData<List<OperationParams>> queryOperationParams(String username){
        return mUserInfoDao.queryOperationParams(username,true);
    }



}
